package notify

import (
	"encoding/csv"
	"errors"
	"os"
)
type UserInfo struct {
	Pos int
	App string
	Mobile string
	OpenId string
}


type CsvConfig struct {
	Dir string
	AppPos int
	MobilePos int
	OpenIdPos int
	StartRow int
}
type LoadingUserInfo func() ([]UserInfo,error)
func LoadUserInfoFromCsvFile(config CsvConfig) LoadingUserInfo{
	return func() ([]UserInfo,error) {

		if config.Dir == "" {
			return nil,errors.New("csv file is empty")
		}
		if config.AppPos <1 || config.MobilePos<1 || config.OpenIdPos<1{
			return nil,errors.New("all pos must to be set and pos>0")
		}
		f, err := os.Open(config.Dir)
		if err != nil{
			return nil,err
		}
		defer f.Close()
		w := csv.NewReader(f)
		data, err := w.ReadAll()
		if err != nil{
			return nil,err
		}
		if len(data)<1{
			return nil,errors.New("no user to send")
		}
		userInfos := make([]UserInfo,0,len(data))
		column := len(data[0])
		for i,val := range data {
			if i<config.StartRow {
				continue
			}
			info := UserInfo{}
			info.Pos = i
			if config.AppPos<=column {
				info.App = val[config.AppPos-1]
			}
			if config.MobilePos<=column {
				info.Mobile = val[config.MobilePos-1]
			}
			if config.OpenIdPos <=column {
				info.OpenId = val[config.OpenIdPos-1]
			}
			userInfos = append(userInfos,info)
		}
		return userInfos,nil
	}
}
